package org.example.mrrope.utils;

import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponse;
import com.aliyun.tea.*;
import com.aliyun.teautil.*;
import com.aliyun.teautil.models.*;
import com.aliyun.dingtalkyida_1_0.models.*;
import com.aliyun.teaopenapi.models.*;
import org.example.mrrope.consts.DingConst;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

import static org.example.mrrope.utils.RetryUtil.retry;

/*
 * Decription:
 * dingding util
 * @author hzk
 * @ClassName dingUtil
 * @Date 2022/3/29 14:29
 */
@Slf4j
@Component
public class DingUtil {
    @Autowired
    private DingConst dingConst;

    /**
     * 使用 Token 初始化账号DingClient
     *
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dingtalkoauth2_1_0.Client createDingClient() throws Exception {
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkoauth2_1_0.Client(config);
    }

    /**
     * 使用 Token 初始化账号YiDaClient
     *
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dingtalkyida_1_0.Client createYiDaClient() throws Exception {
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkyida_1_0.Client(config);
    }

    /***
     * 获取在职人员50人的UserId
     * ByPage
     * @return
     */
    public String getEmployeeQueryonjob(int page) {
        JSONObject object = new JSONObject();
        object.put("status_list", "2,3,5,-1");
        object.put("size", 50);
        object.put("offset", page);
        try {
            return HttpUtil.post("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/queryonjob?access_token=" + getAccessToken(), null, object.toString(), null);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return "";
    }

    /**
     * 获取企业内部应用的accessToken
     *
     * @return
     */
    public String getAccessToken() throws Exception {
        String token = "";
        com.aliyun.dingtalkoauth2_1_0.Client client = DingUtil.createDingClient();
        GetAccessTokenRequest getAccessTokenRequest = new GetAccessTokenRequest()
                .setAppKey(dingConst.getAppKey())
                .setAppSecret(dingConst.getAppSecret());
        try {
            GetAccessTokenResponse accessToken = client.getAccessToken(getAccessTokenRequest);
            //    System.out.println(accessToken.getBody().getExpireIn());
            token = accessToken.getBody().getAccessToken();
            log.info("token-----" + token);
        } catch (TeaException err) {
            if (!Common.empty(err.code) && !Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                log.info("err---" + err);
            }

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!Common.empty(err.code) && !Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                log.info("err---" + err);
            }
        }
        return token;
    }

    /***
     * 解析附件-将宜搭附件下载至本地
     * @param downloadUrl 附件下载地址 /ossFileHandle
     * @param fileName 附件名称  xxx.jpg
     * @param filePath 附件下载路径   C:/HIH3WEB_IMG_CACHE/
     * @return
     */
    public String downloadFj(String downloadUrl, String fileName, String filePath) throws Exception {
        String fileName_OR = filePath + System.currentTimeMillis() + "_" + fileName;
        HttpUtil.downloadUsingNIO(getFjNotLoginUrl(dingConst.getUrl() + downloadUrl), fileName_OR);
        return fileName_OR;
    }

    /***
     * 解析附件-将宜搭附件批量下载至本地
     * @param files 宜搭附件字段数组
     * @param filePath 附件下载路径   C:/HIH3WEB_IMG_CACHE/
     * @return 附件地址数组
     */
    public JSONArray downloadFjs(JSONArray files, String filePath) throws Exception {
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < files.length(); i++) {
            String downloadUrl = files.getJSONObject(i).getString("downloadUrl");
            String name = files.getJSONObject(i).getString("name");
            String s = downloadFj(downloadUrl, name, filePath);
            jsonArray.put(s);
        }
        return jsonArray;
    }

    /**
     * 获取附件免登地址
     *
     * @return
     */
    public String getFjNotLoginUrl(String Url) throws Exception {
        if (!Url.contains(dingConst.getUrl())) {
            Url = dingConst.getUrl() + Url;
        }
        com.aliyun.dingtalkyida_1_0.Client client = DingUtil.createYiDaClient();
        GetOpenUrlHeaders getOpenUrlHeaders = new GetOpenUrlHeaders();
        getOpenUrlHeaders.xAcsDingtalkAccessToken = getAccessToken();
        GetOpenUrlRequest getOpenUrlRequest = new GetOpenUrlRequest()
                .setSystemToken(dingConst.getSystemToken())
                .setUserId(dingConst.getUserId())
                .setLanguage("zh_CN")
                .setFileUrl(Url)
                .setTimeout(60000L);
        try {
            GetOpenUrlResponse openUrlWithOptions = client.getOpenUrlWithOptions(dingConst.getAppType(), getOpenUrlRequest, getOpenUrlHeaders, new RuntimeOptions());
            return openUrlWithOptions.getBody().getResult();
        } catch (TeaException err) {
            if (!Common.empty(err.code) && !Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                System.out.println(err.message);
                System.out.println(err.toString());
                return err.toString();
            }

        } catch (Exception _err) {
            _err.printStackTrace();
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!Common.empty(err.code) && !Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                System.out.println(err.message);
                System.out.println(err.toString());
                return err.toString();
            }
        }
        return "";
    }


    /**
     * @return : String
     * @Description : 精确搜索返回数据
     * @Author : Lizzy
     * @Param : FormUuid
     * @Param : searchFieldJson
     * @Date : 2024/8/30 15:35
     */
    public String yiDaRealSearchReturnData(String FormUuid, JSONArray searchFieldJson) throws Exception {
        JSONArray jarr = new JSONArray();
        int page = 1;
        com.aliyun.dingtalkyida_1_0.Client client = DingUtil.createYiDaClient();
        SearchFormDataSecondGenerationNoTableFieldHeaders searchFormDataSecondGenerationNoTableFieldHeaders = new SearchFormDataSecondGenerationNoTableFieldHeaders();
        searchFormDataSecondGenerationNoTableFieldHeaders.xAcsDingtalkAccessToken = this.getAccessToken();
        while (true) {
            SearchFormDataSecondGenerationNoTableFieldRequest searchFormDataSecondGenerationNoTableFieldRequest = new SearchFormDataSecondGenerationNoTableFieldRequest()
                    .setPageNumber(page)
                    .setAppType(dingConst.getAppType())
                    .setSystemToken(dingConst.getSystemToken())
                    .setUserId(dingConst.getUserId())
                    .setFormUuid(FormUuid)
                    .setSearchCondition(searchFieldJson.toString())
                    .setModifiedFromTimeGMT("2021-05-01 10:10:10")
                    .setPageSize(100);
            try {
                SearchFormDataSecondGenerationNoTableFieldResponse searchFormDataSecondGenerationNoTableFieldResponse = client.searchFormDataSecondGenerationNoTableFieldWithOptions(searchFormDataSecondGenerationNoTableFieldRequest, searchFormDataSecondGenerationNoTableFieldHeaders, new RuntimeOptions());
                Long totalCount = searchFormDataSecondGenerationNoTableFieldResponse.getBody().getTotalCount();
                log.info("yiDaRealSearchReturnData符合查询条件的条数---》" + totalCount);
                if (jarr.isEmpty()) {
                    jarr = new JSONArray(searchFormDataSecondGenerationNoTableFieldResponse.getBody().getData());
                } else {
                    JSONArray newData = new JSONArray(searchFormDataSecondGenerationNoTableFieldResponse.getBody().getData());
                    for (int i = 0; i < newData.length(); i++) {
                        jarr.put(newData.get(i));
                    }
                }
                if (searchFormDataSecondGenerationNoTableFieldResponse.getBody().totalCount > jarr.length()) {
                    page++;
                    continue;
                }
                return jarr.toString();
            } catch (TeaException err) {
                if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                }
            } catch (Exception _err) {
                TeaException err = new TeaException(_err.getMessage(), _err);
                if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                    // err 中含有 code 和 message ���性，可帮助开发定位问题
                }
            }
        }
    }

    /**
     * @return : String
     * @Description : 搜索返回数据
     * @Author : Lizzy
     * @Param : FormUuid
     * @Param : searchFieldJson
     * @Date : 2024/8/30 15:35
     */
    public String yiDaSearchReturnData(String FormUuid, JSONObject searchFieldJson) throws Exception {
        JSONArray jarr = new JSONArray();
        int page = 1;
        com.aliyun.dingtalkyida_1_0.Client client = DingUtil.createYiDaClient();
        SearchFormDatasHeaders searchFormDatasHeaders = new SearchFormDatasHeaders();
        String accessToken = this.getAccessToken();
        searchFormDatasHeaders.xAcsDingtalkAccessToken = accessToken;
        while (true) {
            SearchFormDatasRequest searchFormDatasRequest = new SearchFormDatasRequest()
                    .setAppType(dingConst.getAppType())
                    .setSystemToken(dingConst.getSystemToken())
                    .setUserId(dingConst.getUserId())
                    .setLanguage("zh_CN")
                    .setFormUuid(FormUuid)
                    .setPageSize(100)
                    .setCurrentPage(page)
                    .setSearchFieldJson(searchFieldJson.toString());
            try {
                SearchFormDatasResponse searchFormDatasResponse = client.searchFormDatasWithOptions(searchFormDatasRequest, searchFormDatasHeaders, new RuntimeOptions());
                Long totalCount = searchFormDatasResponse.getBody().getTotalCount();
                log.info("yiDaSearchReturnData符合查询条件的条数---》" + totalCount);
//                return searchFormDataIdListResponse.getBody().getData();
                if (jarr.isEmpty()) {
                    jarr = new JSONArray(searchFormDatasResponse.getBody().getData());
                } else {
                    JSONArray newData = new JSONArray(searchFormDatasResponse.getBody().getData());
                    for (int i = 0; i < newData.length(); i++) {
                        jarr.put(newData.get(i));
                    }
                }
                if (searchFormDatasResponse.getBody().totalCount > jarr.length()) {
                    page++;
                    continue;
                }
                return jarr.toString();
//                reluert = new JSONArray(searchFormDatasResponse.getBody().getData()).toString();
            } catch (TeaException err) {
                err.printStackTrace();
                if (!Common.empty(err.code) && !Common.empty(err.message)) {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                    System.out.println(err.message);
                    System.out.println(err.toString());
                    return err.toString();
                }
            } catch (Exception _err) {
                _err.printStackTrace();
                TeaException err = new TeaException(_err.getMessage(), _err);
                if (!Common.empty(err.code) && !Common.empty(err.message)) {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                    System.out.println(err.message);
                    System.out.println(err.toString());
                    return err.toString();
                }
            }
        }
    }

    /**
     * @return : long
     * @Description : 搜索返回数据条数
     * @Author : Lizzy
     * @Param : FormUuid
     * @Param : searchFieldJson
     * @Date : 2024/8/30 15:34
     */
    public long yiDaSearchReturnCount(String FormUuid, JSONObject searchFieldJson) throws Exception {
        String reluert = "";
        com.aliyun.dingtalkyida_1_0.Client client = DingUtil.createYiDaClient();
        SearchFormDatasHeaders searchFormDatasHeaders = new SearchFormDatasHeaders();
        String accessToken = this.getAccessToken();
        searchFormDatasHeaders.xAcsDingtalkAccessToken = accessToken;
        SearchFormDatasRequest searchFormDatasRequest = new SearchFormDatasRequest()
                .setAppType(dingConst.getAppType())
                .setSystemToken(dingConst.getSystemToken())
                .setUserId(dingConst.getUserId())
                .setLanguage("zh_CN")
                .setFormUuid(FormUuid)
                .setPageSize(100)
                .setCurrentPage(1)
                .setSearchFieldJson(searchFieldJson.toString());
        try {
            SearchFormDatasResponse searchFormDatasResponse = client.searchFormDatasWithOptions(searchFormDatasRequest, searchFormDatasHeaders, new RuntimeOptions());
            return searchFormDatasResponse.getBody().getTotalCount();
        } catch (TeaException err) {
            err.printStackTrace();
            if (!Common.empty(err.code) && !Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                System.out.println(err.message);
                System.out.println(err.toString());
                return 0l;
            }
        } catch (Exception _err) {
            _err.printStackTrace();
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!Common.empty(err.code) && !Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                System.out.println(err.message);
                System.out.println(err.toString());
                return 0l;
            }
        }
        return 0l;
    }

    /**
     * @return : String
     * @Description : 通过页码搜索返回数据
     * @Author : Lizzy
     * @Param : FormUuid
     * @Param : searchFieldJson
     * @Param : page
     * @Date : 2024/8/30 15:34
     */
    public String yiDaSearchReturnDataByPage(String FormUuid, JSONObject searchFieldJson, int page) throws Exception {
        String reluert = "";
        com.aliyun.dingtalkyida_1_0.Client client = DingUtil.createYiDaClient();
        SearchFormDatasHeaders searchFormDatasHeaders = new SearchFormDatasHeaders();
        String accessToken = this.getAccessToken();
        searchFormDatasHeaders.xAcsDingtalkAccessToken = accessToken;
        SearchFormDatasRequest searchFormDatasRequest = new SearchFormDatasRequest()
                .setAppType(dingConst.getAppType())
                .setSystemToken(dingConst.getSystemToken())
                .setUserId(dingConst.getUserId())
                .setLanguage("zh_CN")
                .setFormUuid(FormUuid)
                .setPageSize(100)
                .setCurrentPage(page)
                .setSearchFieldJson(searchFieldJson.toString());
        try {
            SearchFormDatasResponse searchFormDatasResponse = client.searchFormDatasWithOptions(searchFormDatasRequest, searchFormDatasHeaders, new RuntimeOptions());
            reluert = new JSONArray(searchFormDatasResponse.getBody().getData()).toString();
        } catch (TeaException err) {
            err.printStackTrace();
            if (!Common.empty(err.code) && !Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                System.out.println(err.message);
                System.out.println(err.toString());
                return err.toString();
            }
        } catch (Exception _err) {
            _err.printStackTrace();
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!Common.empty(err.code) && !Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                System.out.println(err.message);
                System.out.println(err.toString());
                return err.toString();
            }
        }
        return reluert;
    }

    /**
     * @return : String
     * @Description : 获取表单全部实例ID
     * @Author : Lizzy
     * @Param : fromUuid
     * @Date : 2024/8/30 15:47
     */
    public String getAllYiDaIds(String fromUuid) throws Exception {
        com.aliyun.dingtalkyida_1_0.Client client = DingUtil.createYiDaClient();
        SearchFormDataIdListHeaders searchFormDataIdListHeaders = new SearchFormDataIdListHeaders();
        searchFormDataIdListHeaders.xAcsDingtalkAccessToken = this.getAccessToken();
        SearchFormDataIdListRequest searchFormDataIdListRequest = new SearchFormDataIdListRequest()
                .setSystemToken(dingConst.getSystemToken())
                .setUserId(dingConst.getUserId());
        try {
            SearchFormDataIdListResponse searchFormDataIdListResponse = client.searchFormDataIdListWithOptions(dingConst.getAppType(), fromUuid, searchFormDataIdListRequest, searchFormDataIdListHeaders, new RuntimeOptions());
            Long totalCount = searchFormDataIdListResponse.getBody().getPageNumber();
//            System.out.println(totalCount);
            log.info("总条数---》" + totalCount);
            return searchFormDataIdListResponse.getBody().getData().toString();
        } catch (TeaException err) {
            err.printStackTrace();
            if (!Common.empty(err.code) && !Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                System.out.println(err.message);
                System.out.println(err.toString());
                return err.toString();
            }

        } catch (Exception _err) {
            _err.printStackTrace();
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!Common.empty(err.code) && !Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                System.out.println(err.message);
                System.out.println(err.toString());
                return err.toString();
            }
        }
        return "";
    }

    /**
     * @return : List<String>
     * @Description : 获取表内符合条件的id列表
     * @Author : Lizzy
     * @Param : fromUuid
     * @Param : searchJsonString
     * @Date : 2024/8/30 15:48
     */
    public List<String> getYiDaIds(String fromUuid, String searchJsonString) throws Exception {
        List<String> jarr = new ArrayList<>();
        int page = 1;
        while (true) {
            com.aliyun.dingtalkyida_1_0.Client client = DingUtil.createYiDaClient();
            SearchFormDataIdListHeaders searchFormDataIdListHeaders = new SearchFormDataIdListHeaders();
            searchFormDataIdListHeaders.xAcsDingtalkAccessToken = this.getAccessToken();
            SearchFormDataIdListRequest searchFormDataIdListRequest = new SearchFormDataIdListRequest()
                    .setSystemToken(dingConst.getSystemToken())
                    .setLanguage("zh_CN")
                    .setSearchFieldJson(searchJsonString)
                    .setUserId(dingConst.getUserId())
                    .setLanguage("zh_CN")
                    .setPageSize(100)
                    .setPageNumber(page);
            try {
                SearchFormDataIdListResponse searchFormDataIdListResponse = client.searchFormDataIdListWithOptions(dingConst.getAppType(), fromUuid, searchFormDataIdListRequest, searchFormDataIdListHeaders, new RuntimeOptions());
                Long totalCount = searchFormDataIdListResponse.getBody().getTotalCount();
                log.info("getYiDaIds符合查询条件的条数---》" + totalCount);
//                return searchFormDataIdListResponse.getBody().getData();
                if (jarr.isEmpty()) {
                    jarr = searchFormDataIdListResponse.getBody().getData();
                } else {
                    jarr.addAll(searchFormDataIdListResponse.getBody().getData());
                }
                if (searchFormDataIdListResponse.getBody().totalCount > jarr.size()) {
                    page++;
                    continue;
                }
                return jarr;
            } catch (TeaException err) {
                if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                    log.info("getYiDaIds err.code:" + err.code + " err.message:" + err.message);
                    break;
                }
            } catch (Exception _err) {
                TeaException err = new TeaException(_err.getMessage(), _err);
                if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                    log.info("getYiDaIds err.code:" + err.code + " err.message:" + err.message);
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                    break;
                }
            }
        }
        return jarr;
    }


    public List<String> getInstanceIdList(String fromUuid) throws Exception {
        List<String> jarr = new ArrayList<>();
        int page = 1;
        com.aliyun.dingtalkyida_1_0.Client client = DingUtil.createYiDaClient();
        GetInstanceIdListHeaders getInstanceIdListHeaders = new GetInstanceIdListHeaders();
        getInstanceIdListHeaders.xAcsDingtalkAccessToken = this.getAccessToken();
        while (true) {
            GetInstanceIdListRequest getInstanceIdListRequest = new GetInstanceIdListRequest()
                    .setPageSize(100)
                    .setPageNumber(page)
                    .setFormUuid(fromUuid)
                    .setSystemToken(dingConst.getSystemToken())
                    .setLanguage("zh_CN")
                    .setSearchFieldJson("")
                    .setUserId(dingConst.getUserId())
                    .setAppType("APP_STOGL8LBF88ZMSIXMPPW");
            try {
                GetInstanceIdListResponse instanceIdListWithOptions = client.getInstanceIdListWithOptions(getInstanceIdListRequest, getInstanceIdListHeaders, new RuntimeOptions());
                Long totalCount = instanceIdListWithOptions.getBody().getTotalCount();
                log.info("getYiDaIds符合查询条件的条数---》" + totalCount);
//                return searchFormDataIdListResponse.getBody().getData();
                if (jarr.isEmpty()) {
                    jarr = instanceIdListWithOptions.getBody().getData();
                } else {
                    jarr.addAll(instanceIdListWithOptions.getBody().getData());
                }
                if (instanceIdListWithOptions.getBody().totalCount > jarr.size()) {
                    page++;
                    continue;
                }
                return jarr;
            } catch (TeaException err) {
                if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                }
            } catch (Exception _err) {
                TeaException err = new TeaException(_err.getMessage(), _err);
                if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                }
            }
        }
    }

    /**
     * @return : String
     * @Description : 根据ID查询宜搭数据
     * @Author : Lizzy
     * @Param : id
     * @Date : 2024/8/30 15:48
     */
    public String getYidaById(String id) throws Exception {
        log.info("getYidaById测试id：" + id);
        com.aliyun.dingtalkyida_1_0.Client client = DingUtil.createYiDaClient();
        GetFormDataByIDHeaders getFormDataByIDHeaders = new GetFormDataByIDHeaders();
        getFormDataByIDHeaders.xAcsDingtalkAccessToken = this.getAccessToken();
        GetFormDataByIDRequest getFormDataByIDRequest = new GetFormDataByIDRequest()
                .setAppType(dingConst.getAppType())
                .setSystemToken(dingConst.getSystemToken())
                .setUserId(dingConst.getUserId())
                .setLanguage("zh_CN");
        try {
            log.info("进入方法");
            GetFormDataByIDResponse formDataByIDWithOptions = client.getFormDataByIDWithOptions(id, getFormDataByIDRequest, getFormDataByIDHeaders, new RuntimeOptions());
//            log.info("formDataByIDWithOptions:" + formDataByIDWithOptions.getBody().getFormData() + "id:" + id);
            return new JSONObject(formDataByIDWithOptions.getBody().getFormData()).put("userId", formDataByIDWithOptions.body.getOriginator().getUserId()).toString();
        } catch (TeaException err) {
            err.printStackTrace();
            if (!Common.empty(err.code) && !Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题-
                log.info("错误1");
                log.info(err.message);
                log.info(err.toString());
                System.out.println(err.message);
                System.out.println(err.toString());
                return err.toString();
            }
        } catch (Exception _err) {
            _err.printStackTrace();
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!Common.empty(err.code) && !Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                log.info("错误2");
                log.info(err.message);
                log.info(err.toString());
                System.out.println(err.message);
                System.out.println(err.toString());
                return err.toString();
            }
        }
        return "";
    }

    public String getYidamodifiedTimeGMTById(String id) throws Exception {
        log.info("getYidaById测试id：" + id);
        com.aliyun.dingtalkyida_1_0.Client client = DingUtil.createYiDaClient();
        GetFormDataByIDHeaders getFormDataByIDHeaders = new GetFormDataByIDHeaders();
        getFormDataByIDHeaders.xAcsDingtalkAccessToken = this.getAccessToken();
        GetFormDataByIDRequest getFormDataByIDRequest = new GetFormDataByIDRequest()
                .setAppType(dingConst.getAppType())
                .setSystemToken(dingConst.getSystemToken())
                .setUserId(dingConst.getUserId())
                .setLanguage("zh_CN");
        try {
            log.info("进入方法");
            GetFormDataByIDResponse formDataByIDWithOptions = client.getFormDataByIDWithOptions(id, getFormDataByIDRequest, getFormDataByIDHeaders, new RuntimeOptions());
//            log.info("formDataByIDWithOptions:" + formDataByIDWithOptions.getBody().getFormData() + "id:" + id);
            return formDataByIDWithOptions.getBody().getModifiedTimeGMT();
        } catch (TeaException err) {
            err.printStackTrace();
            if (!Common.empty(err.code) && !Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题-
                log.info("错误1");
                log.info(err.message);
                log.info(err.toString());
                System.out.println(err.message);
                System.out.println(err.toString());
                return err.toString();
            }
        } catch (Exception _err) {
            _err.printStackTrace();
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!Common.empty(err.code) && !Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                log.info("错误2");
                log.info(err.message);
                log.info(err.toString());
                System.out.println(err.message);
                System.out.println(err.toString());
                return err.toString();
            }
        }
        return "";
    }


    /**
     * @return : JSONArray
     * @Description : 获得子表组件数据
     * @Param : id
     * @Param : formuuid
     * @Param : fieldId
     * @Date : 2024/7/25 13:25
     */
    public JSONArray getInnerTables(String id, String formuuid, String fieldId) throws Exception {
        JSONArray jarr = new JSONArray();
        int page = 1;
        while (true) {
            com.aliyun.dingtalkyida_1_0.Client client = DingUtil.createYiDaClient();
            ListTableDataByFormInstanceIdTableIdHeaders listTableDataByFormInstanceIdTableIdHeaders = new ListTableDataByFormInstanceIdTableIdHeaders();
            listTableDataByFormInstanceIdTableIdHeaders.xAcsDingtalkAccessToken = this.getAccessToken();
            ListTableDataByFormInstanceIdTableIdRequest listTableDataByFormInstanceIdTableIdRequest = new ListTableDataByFormInstanceIdTableIdRequest()
                    .setFormUuid(formuuid)
                    .setTableFieldId(fieldId)
                    .setPageNumber(page)
                    .setPageSize(50)
                    .setAppType(dingConst.getAppType())
                    .setSystemToken(dingConst.getSystemToken())
                    .setUserId(dingConst.getUserId());
            try {
                ListTableDataByFormInstanceIdTableIdResponse listTableDataByFormInstanceIdTableIdResponse = client.listTableDataByFormInstanceIdTableIdWithOptions(id, listTableDataByFormInstanceIdTableIdRequest, listTableDataByFormInstanceIdTableIdHeaders, new RuntimeOptions());

                if (jarr.isEmpty()) {
                    jarr = new JSONArray(listTableDataByFormInstanceIdTableIdResponse.getBody().data);
                } else {
                    for (int i = 0; i < listTableDataByFormInstanceIdTableIdResponse.getBody().data.size(); i++) {
                        jarr.put(listTableDataByFormInstanceIdTableIdResponse.getBody().data.get(i));
                    }
                }
                if (listTableDataByFormInstanceIdTableIdResponse.getBody().totalCount > jarr.length()) {
                    page++;
                    continue;
                }
                return jarr;
            } catch (TeaException err) {
                if (!Common.empty(err.code) && !Common.empty(err.message)) {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                    break;
                }
            } catch (Exception _err) {
                TeaException err = new TeaException(_err.getMessage(), _err);
                if (!Common.empty(err.code) && !Common.empty(err.message)) {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                    break;
                }
            }
        }
        return jarr;
    }

    /**
     * @return : String
     * @Description : 发起流程数据
     * @Author : Lizzy
     * @Param : jsonObject 数据
     * @Param : userId 发起人id
     * @Param : FormUuid 表单id
     * @Date : 2024/8/30 15:49
     */
    public String startInstance(JSONObject jsonObject, String userId, String FormUuid) throws Exception {
        com.aliyun.dingtalkyida_1_0.Client client = DingUtil.createYiDaClient();
        StartInstanceHeaders startInstanceHeaders = new StartInstanceHeaders();
        startInstanceHeaders.xAcsDingtalkAccessToken = this.getAccessToken();
        StartInstanceRequest startInstanceRequest = new StartInstanceRequest()
                .setAppType(dingConst.getAppType())
                .setSystemToken(dingConst.getSystemToken())
                .setUserId(userId)
                .setLanguage("zh_CN")
                .setFormUuid(FormUuid)
                .setFormDataJson(jsonObject.toString());
        try {
            StartInstanceResponse startInstanceResponse = client.startInstanceWithOptions(startInstanceRequest, startInstanceHeaders, new RuntimeOptions());
            log.info("返回值:--------------------------" + startInstanceResponse.getBody().toMap().toString());
            log.info("startInstanceHeaders" + startInstanceHeaders.toString());
            return new JSONObject(startInstanceResponse.getBody().toMap()).toString();
        } catch (TeaException err) {
            if (!Common.empty(err.code) && !Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                System.out.println(err.message);
                System.out.println(err.toString());
                return err.toString();
            }
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!Common.empty(err.code) && !Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                System.out.println(err.message);
                System.out.println(err.toString());
                return err.toString();
            }
        }
        return "";
    }

    /**
     * @return : String
     * @Description : 新增表单数据
     * @Author : Lizzy
     * @Param : FormUuid 表id
     * @Param : jo 数据
     * @Param : userId 发起人
     * @Date : 2024/8/30 15:50
     */
    public String saveYiDa(String FormUuid, JSONObject jo, String userId) throws Exception {
        if ("".equals(userId)) {
            userId = dingConst.getUserId();
        }
        com.aliyun.dingtalkyida_1_0.Client client = DingUtil.createYiDaClient();
        SaveFormDataHeaders saveFormDataHeaders = new SaveFormDataHeaders();
        saveFormDataHeaders.xAcsDingtalkAccessToken = this.getAccessToken();
        SaveFormDataRequest saveFormDataRequest = new SaveFormDataRequest()
                .setAppType(dingConst.getAppType())
                .setSystemToken(dingConst.getSystemToken())
                .setUserId(userId)
                .setLanguage("zh_CN")
                .setFormUuid(FormUuid)
                .setFormDataJson(jo.toString());
        try {
            SaveFormDataResponse saveFormDataResponse = client.saveFormDataWithOptions(saveFormDataRequest, saveFormDataHeaders, new RuntimeOptions());
            return new JSONObject(saveFormDataResponse.getBody().toMap()).toString();
        } catch (TeaException err) {
            err.printStackTrace();
            if (!Common.empty(err.code) && !Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                System.out.println(err.message);
                System.out.println(err.toString());
                return err.toString();
            }
        } catch (Exception _err) {
            _err.printStackTrace();
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!Common.empty(err.code) && !Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                System.out.println(err.message);
                System.out.println(err.toString());
                return err.toString();
            }
        }
        return "";
    }

    /**
     * @return : String
     * @Description : 修改数据
     * @Author : Lizzy
     * @Param : formInstanceId 表单数据id
     * @Param : jo 数据
     * @Date : 2024/8/30 15:51
     */
    public String UpdateYiDa(String formInstanceId, JSONObject jo) throws Exception {
        com.aliyun.dingtalkyida_1_0.Client client = DingUtil.createYiDaClient();
        UpdateFormDataHeaders updateFormDataHeaders = new UpdateFormDataHeaders();
        updateFormDataHeaders.xAcsDingtalkAccessToken = this.getAccessToken();
        UpdateFormDataRequest updateFormDataRequest = new UpdateFormDataRequest()
                .setAppType(dingConst.getAppType())
                .setSystemToken(dingConst.getSystemToken())
                .setUserId(dingConst.getUserId())
                .setLanguage("zh_CN")
                .setFormInstanceId(formInstanceId)
                .setUpdateFormDataJson(jo.toString())
                .setUseLatestVersion(true);
        try {
//            String result = retry(() -> {
//                // 这里放置可能会失败的操作
//                try {
//                    log.info("更新开始");
//                    client.updateFormDataWithOptions(updateFormDataRequest, updateFormDataHeaders, new RuntimeOptions());
//                } catch (Exception e) {
//                    throw new RuntimeException(e);
//                }
//                return "Success";
//            }, 3, 1000); // 最多重试3次，每次间隔1秒
//            System.out.println(result);
            log.info("更新开始-----{}", formInstanceId);
            UpdateFormDataResponse updateFormDataResponse = client.updateFormDataWithOptions(updateFormDataRequest, updateFormDataHeaders, new RuntimeOptions());
            log.info("更新返回值:--------------------------" + updateFormDataResponse.getStatusCode());
            log.info("更新返回值:--------------------------" + updateFormDataResponse.getHeaders());
            return new JSONObject(updateFormDataResponse.getHeaders()).toString();
        } catch (TeaException err) {
            err.printStackTrace();
            if (!Common.empty(err.code) && !Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                log.info(err.message);
                log.info(err.toString());
                System.out.println(err.message);
                System.out.println(err.toString());
                return err.toString();
            }
        } catch (Exception _err) {
            _err.printStackTrace();
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!Common.empty(err.code) && !Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                log.info(err.message);
                log.info(err.toString());
                System.out.println(err.message);
                System.out.println(err.toString());
                return err.toString();
            }
        }
        return "";
    }

    /**
     * @return : String
     * @Description : 删除流程数据
     * @Author : Lizzy
     * @Param : instanceid
     * @Date : 2024/8/30 15:52
     */
    public String delete(String instanceid) {
        try {
            com.aliyun.dingtalkyida_1_0.Client client = DingUtil.createYiDaClient();
            DeleteFormDataHeaders deleteFormDataHeaders = new DeleteFormDataHeaders();
            deleteFormDataHeaders.xAcsDingtalkAccessToken = this.getAccessToken();
            DeleteFormDataRequest deleteFormDataRequest = new DeleteFormDataRequest()
                    .setAppType(dingConst.getAppType())
                    .setSystemToken(dingConst.getSystemToken())
                    .setUserId(dingConst.getUserId())
                    .setLanguage("zh_CN")
                    .setFormInstanceId(instanceid);
            DeleteFormDataResponse deleteFormDataResponse = client.deleteFormDataWithOptions(deleteFormDataRequest, deleteFormDataHeaders, new RuntimeOptions());
            return deleteFormDataResponse.toString();
        } catch (TeaException err) {
            if (!Common.empty(err.code) && !Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                System.out.println(err.message);
                System.out.println(err.toString());
                return err.toString();
            }
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!Common.empty(err.code) && !Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                System.out.println(err.message);
                System.out.println(err.toString());
                return err.toString();
            }
        }
        return "";
    }

    /**
     * @return : String
     * @Description : 表单的新增或更新
     * @Author : Lizzy
     * @Param : formUuid 表单uuid
     * @Param : searchCondition 高级查询条件
     * @Param : formDataJson 更新json数据
     * @Date : 2024/8/30 16:05
     */
    public String CreateOrUpdateFormDataRequest(String formUuid, String searchCondition, String formDataJson) throws
            Exception {
        try {
            com.aliyun.dingtalkyida_1_0.Client client = DingUtil.createYiDaClient();
            CreateOrUpdateFormDataHeaders createOrUpdateFormDataHeaders = new CreateOrUpdateFormDataHeaders();
            createOrUpdateFormDataHeaders.xAcsDingtalkAccessToken = this.getAccessToken();
            CreateOrUpdateFormDataRequest createOrUpdateFormDataRequest = new CreateOrUpdateFormDataRequest()
                    .setNoExecuteExpression(false)
                    .setFormUuid(formUuid)
                    .setSearchCondition(searchCondition)
                    .setFormDataJson(formDataJson)
                    .setAppType(dingConst.getAppType())
                    .setSystemToken(dingConst.getSystemToken())
                    .setUserId(dingConst.getUserId());
            CreateOrUpdateFormDataResponse upsertFormDataWithOptions = client.createOrUpdateFormDataWithOptions(createOrUpdateFormDataRequest, createOrUpdateFormDataHeaders, new RuntimeOptions());
            return upsertFormDataWithOptions.toString();
        } catch (TeaException err) {
            if (!Common.empty(err.code) && !Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                System.out.println(err.message);
                System.out.println(err.toString());
                return err.toString();
            }
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!Common.empty(err.code) && !Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                System.out.println(err.message);
                System.out.println(err.toString());
                return err.toString();
            }
        }
        return "";
    }


}

